package com.gengzp.system.facade.impl;

import com.gengzp.common.enums.ConsolePageEnum;
import com.gengzp.common.enums.PermissionEnum;
import com.gengzp.common.exception.BusinessException;
import com.gengzp.common.model.permission.dto.ConsolePageDto;
import com.gengzp.common.model.permission.dto.PermissionDto;
import com.gengzp.common.model.permission.entity.UserRoleRelation;
import com.gengzp.permission.utils.PermissionUtils;
import com.gengzp.system.facade.PermissionFacade;
import com.gengzp.system.mapper.UserRoleRelationMapper;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName PermissionFacadeImpl
 * @Description 权限模块服务层实现类
 * @Author gengzp
 * @Date 2025/9/19 11:42
 */
@Service
public class PermissionFacadeImpl implements PermissionFacade {

    @Autowired
    private UserRoleRelationMapper userRoleRelationMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeUserRoleRelationsByRoleId(Long roleId) {
        if (Objects.isNull(roleId)) {
            throw BusinessException.get("角色id不能为空");
        }
        userRoleRelationMapper.deleteUserRoleRelationsByRoleId(roleId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeUserRoleRelationsByUserId(Long userId) {
        if (Objects.isNull(userId)) {
            throw BusinessException.get("用户id不能为空");
        }
        userRoleRelationMapper.deleteUserRoleRelationsByUserId(userId);
    }

    @Override
    public List<Long> searchRoleIdsByUserId(Long userId) {
        if (Objects.isNull(userId)) {
            throw BusinessException.get("用户id不能为空");
        }

        return userRoleRelationMapper.selectRoleIdsByUserId(userId);
    }

    @Override
    public List<String> searchAllLeafPermissionCodes() {
        // 1. 收集所有权限中作为"父权限编码"的值（即所有有子权限的编码）
        Set<String> allParentCodes = new HashSet<>();
        for (PermissionEnum permission : PermissionEnum.values()) {
            if (Objects.nonNull(permission.getParentPermission())) {
                allParentCodes.add(permission.getParentPermission().getCode());
            }
        }

        // 2. 筛选出"自身编码不在父权限编码集合中"的权限（这些就是最底层权限）
        List<String> bottomPermissionCodes = new ArrayList<>();
        for (PermissionEnum permission : PermissionEnum.values()) {
            if (!allParentCodes.contains(permission.getCode())) {
                bottomPermissionCodes.add(permission.getCode());
            }
        }

        return bottomPermissionCodes;
    }

    @Override
    public List<String> searchAllConsolePageCodes() {
        return Arrays.stream(ConsolePageEnum.values())
                .map(ConsolePageEnum::getCode).collect(Collectors.toList());
    }

    @Override
    public List<Long> searchUserIdsByRoleId(Long roleId) {
        if (Objects.isNull(roleId)) {
            throw BusinessException.get("角色id不能为空");
        }
        return userRoleRelationMapper.selectUserIdsByRoleId(roleId);
    }

    @Override
    public List<UserRoleRelation> searchUserRoleRelationsByRoleIds(List<Long> roleIds) {
        if (CollectionUtils.isEmpty(roleIds)) {
            return Lists.newArrayList();
        }
        return userRoleRelationMapper.selectUserRoleRelationsByRoleIds(roleIds);
    }

    @Override
    public List<PermissionDto> searchPermissionDtosByPermissionCodes(List<String> permissionCodes) {
        List<PermissionDto> permissionDtos = Lists.newArrayList();
        for (String permissionCode : permissionCodes) {
            PermissionEnum permission = PermissionEnum.getByCode(permissionCode);
            if (Objects.isNull(permission)) {
                continue;
            }

            PermissionDto permissionDto = new PermissionDto();
            permissionDto.setPermissionCode(permission.getCode());
            permissionDto.setPermissionName(permission.getName());
            permissionDto.setPermissionDescription(permission.getDescription());
            permissionDtos.add(permissionDto);
        }

        return permissionDtos;
    }

    @Override
    public List<ConsolePageDto> searchConsolePagesByPageCodes(List<String> pageCodes) {
        List<ConsolePageDto> consolePageDtos = Lists.newArrayList();
        for (String pageCode : pageCodes) {
            ConsolePageEnum consolePageEnum = ConsolePageEnum.getByCode(pageCode);
            if (Objects.isNull(consolePageEnum)) {
                continue;
            }

            ConsolePageDto consolePageDto = new ConsolePageDto();
            consolePageDto.setPageCode(consolePageEnum.getCode());
            consolePageDto.setPageName(consolePageEnum.getName());
            consolePageDto.setModule(consolePageEnum.getModule());
            consolePageDtos.add(consolePageDto);
        }

        // 根据模块名排序, 让相同的模块名对应的页面权限能展示在一起
        consolePageDtos.sort(Comparator.comparing(ConsolePageDto::getModule));

        return consolePageDtos;
    }

}
